import requests
import time

BASE = "http://localhost:8080"

def create_error_task():
    """创建一个会产生错误的任务"""
    data = {
        "name": "error-demo-task",
        "direction": "KAFKA_TO_RABBIT",
        "kafkaSourceBootstrap": "192.168.168.23:9092",
        "kafkaSourceTopic": "test_topic",  # 存在的topic
        "kafkaSourceGroup": "error-demo-group",
        "kafkaSourceOffsetReset": "latest",
        "rabbitTargetHost": "192.168.168.23",
        "rabbitTargetPort": 5672,
        "rabbitTargetVhost": "/",
        "rabbitTargetUsername": "guest",
        "rabbitTargetPassword": "guest",
        "rabbitTargetExchange": "",
        "rabbitTargetRoutingKey": "nonexistent_error_queue",  # 不存在的队列，会导致错误
        "enabled": True,
        "concurrency": 1,
        "maxRetries": 3,
        "retryBackoffMs": 1000
    }
    r = requests.post(BASE + "/api/tasks", json=data)
    r.raise_for_status()
    return r.json()

def send_test_messages():
    """发送一些测试消息到Kafka来触发错误"""
    from kafka import KafkaProducer
    import json
    
    try:
        producer = KafkaProducer(
            bootstrap_servers=['192.168.168.23:9092'],
            value_serializer=lambda x: json.dumps(x).encode('utf-8')
        )
        
        # 发送多条消息
        for i in range(5):
            message = {"test": f"error message {i+1}", "timestamp": time.time()}
            producer.send('test_topic', message)
            print(f"发送消息 {i+1}")
        
        producer.flush()
        print("所有消息发送完成")
    except Exception as e:
        print(f"发送消息失败: {e}")

if __name__ == "__main__":
    print("创建错误演示任务...")
    
    # 创建任务
    task = create_error_task()
    print(f"创建了任务: {task['id']} - {task['name']}")
    
    # 启动任务
    print("启动任务...")
    requests.post(f"{BASE}/api/tasks/{task['id']}/start")
    
    # 等待一下让任务启动
    time.sleep(2)
    
    # 发送消息触发错误
    print("发送测试消息...")
    send_test_messages()
    
    # 等待处理
    print("等待消息处理...")
    time.sleep(10)
    
    # 停止任务
    print("停止任务...")
    requests.post(f"{BASE}/api/tasks/{task['id']}/stop")
    
    # 检查任务状态
    print("检查任务状态...")
    response = requests.get(f"{BASE}/api/tasks")
    tasks = response.json()
    
    for t in tasks:
        if t['id'] == task['id']:
            print(f"任务 {t['name']}:")
            print(f"  处理: {t['processed']}")
            print(f"  失败: {t['failed']}")
            print(f"  错误信息: {t['lastErrorMsg']}")
            break
    
    print("完成！现在刷新前端页面应该能看到失败统计了。")
